/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:
 * Date: 2024-11-08
 * Time: 19:08
 */
import java.util.Stack;

public class BracketMatcher {
    // 检查括号是否匹配
    public static boolean isBalanced(String expression) {
        Stack<Character> stack = new Stack<>();
        for (char ch : expression.toCharArray()) {
            switch (ch) {
                case '{':
                case '(':
                case '[':
                    stack.push(ch);
                    break;
                case '}':
                    if (stack.isEmpty() || stack.pop() != '{') return false;
                    break;
                case ')':
                    if (stack.isEmpty() || stack.pop() != '(') return false;
                    break;
                case ']':
                    if (stack.isEmpty() || stack.pop() != '[') return false;
                    break;
                default:
                    // 忽略非括号字符
                    break;
            }
        }
        return stack.isEmpty();
    }

    public static void main(String[] args) {
        // 测试括号匹配
        String expression1 = "{[()()]()}";
        String expression2 = "{[(])}";
        String expression3 = "{[(])";

        System.out.println("Expression 1 balanced: " + isBalanced(expression1));
        System.out.println("Expression 2 balanced: " + isBalanced(expression2));
        System.out.println("Expression 3 balanced: " + isBalanced(expression3));
    }
}